$(function() {
	let newsClassIdObj = $("select[name='newsClassId']");
	$.get(
		"news-class-json.do",
		function(data) {
			$.each(data, function(i, item) {
				$("<option></option>")
					.text(item.newsClassName)
					.val(item.newsClassId)
					.appendTo(newsClassIdObj);
			});
		}, "json"
	);

	let page;

	/**
	 * 查询条件
	 */
	let params = "";
	/**
	 * 处理查询条件
	 */
	let searchForm = $("._searchForm");
	searchForm.submit(function() {
		params = searchForm.serialize();
		loadData();
		return false;
	})

	/**
	 * 加载分页数据
	 * @param {int} current
	 */
	let loadData = function(current = 1) {
		$.get(
			"news-manage.do",
			params + "&current=" + current + "&status=2",
			function(data) {
				formatData(data.list);
				formatPage(data);
			}, "json"
		);
	}
	let datagrid = $("#datagrid");
	let template = datagrid.children().remove();
	/**
	 * 格式化数据
	 * @param {Object} list
	 */
	let formatData = function(list) {
		datagrid.empty();
		$.each(list, function(i, item) {
			let tr = template.clone().appendTo(datagrid);
			let reportRealName;
			item.rowNumber = i + 1;
			$.each(item, function(name, value) {
				tr.find("._" + name).text(value);
			});
			$.post(
				"user/get-realName.do",
				"userName=" + item.newsManager,
				function(data) {
					fn1(data);
				}, "json"
			)
			let fn1 = function(data) {
				tr.find("._newsManager").text(data.userRealName);
			}
			if(item.newsStatus == 0) {
				tr.find("._newsHandle  option:eq(0)").attr('selected', 'selected');
			}
			if(item.newsStatus == 1) {
				tr.find("._newsHandle  option:eq(1)").attr('selected', 'selected');
			}
			if(item.newsStatus == 2) {
				tr.find("._newsHandle  option:eq(2)").attr('selected', 'selected');
			}
			tr.find("._del").attr("data-id", item.newsId);
			tr.find("._newsTitle").attr("href", "news-show-" + item.newsId + ".html")
		});
	}

	let pagination = $(".pagination");
	let liTemplate = pagination.children(":eq(1)").remove();
	/**
	 * 格式化页码
	 * @param {Object} p
	 */
	let formatPage = function(p) {
		pagination.children(":not(:eq(0),:eq(-1))").remove();

		pagination.children(":last").attr("data-page", p.pages);

		$.each(p.navigatepageNums, function(index, i) {
			let li = liTemplate.clone().insertBefore(pagination.children(":eq(-1)"));
			li.children("a").text(i);
			li.attr("data-page", i);
			if(p.pageNum == i) {
				li.addClass("active");
			}
		});

	}

	/**
	 * 处理分页事件
	 */
	pagination.on("click", "[data-page]", function() {
		page = $(this).data("page");
		loadData(page);
	});

	loadData();

	$("body").on("click", "._del", function() {
		$.post(
			"news-manage-delete.do", 
			{"newsId": $(this).data("id")},
			function(data) {
				if(data.ok) {
					toastr.success("删除成功");
					$("._searchForm").trigger("submit");
				} else {
					toastr.error("删除失败：" + data.message);
				}
			}, "json"

		)
	})
});